package ClientPackage;

import SecureUtil.Packer;
import java.net.InetAddress;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.SecretKey;

public class ClientInfo {
	public SecretKey _sessionkey;
	public PublicKey _pubkey;
	public InetAddress _ip;
	public int _port;
    public String _username;
    
    public ClientInfo(InetAddress IP, int Port, String uName){
    	_ip = IP;
    	_port = Port;  	
    	_username = uName;
    }
    /**
     * convert username, ip, port, pubkey to byte array for send
     * @return the byte of packed username,ip, port, pubkey
     */
    public byte[] toByteArray() throws Exception{
        Packer packer = new Packer();
        packer.addElement(Packer.DataType.STRING,_username);
        packer.addElement(Packer.DataType.STRING, _ip.getHostAddress());
        packer.addElement(Packer.DataType.INTEGER, new Integer(_port));
        packer.addElement(Packer.DataType.BYTES, _pubkey.getEncoded());
        return packer.pack();
    }
    public ClientInfo(byte[] raw) throws Exception{
        Packer packer = new Packer();
        packer.unpack(raw);
        this._username = (String) packer.getNext(Packer.DataType.STRING);
        String hostname = (String) packer.getNext(Packer.DataType.STRING);
        this._ip = InetAddress.getByName(hostname);
        this._port = (Integer) packer.getNext(Packer.DataType.INTEGER);
        byte[] pubkeycode = (byte[]) packer.getNext(Packer.DataType.BYTES);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubkeycode);
        this._pubkey = keyFactory.generatePublic(publicKeySpec);
    }
}
